package edu.nf.project.webs.storeOperation;

import edu.nf.project.services.exception.derivedAnomalies.OrderStatisticsException;
import edu.nf.project.services.storeOperation.OrderStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 订单统计Controller
 */
@RestController
@RequestMapping("/api/statistics")
public class OrderStatisticsController {

    @Autowired
    private OrderStatisticsService orderStatisticsService;

    /**
     * 获取总营业额
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 总营业额
     */
    @GetMapping("/revenue")
    public BigDecimal getTotalRevenue(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        try {
            return orderStatisticsService.getTotalRevenue(startTime, endTime);
        } catch (OrderStatisticsException e) {
            throw e;
        } catch (Exception e) {
            throw new OrderStatisticsException(70000, "获取总营业额失败：" + e.getMessage());
        }
    }

    /**
     * 获取总订单数
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 总订单数
     */
    @GetMapping("/count")
    public Long getTotalOrderCount(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        try {
            return orderStatisticsService.getTotalOrderCount(startTime, endTime);
        } catch (OrderStatisticsException e) {
            throw e;
        } catch (Exception e) {
            throw new OrderStatisticsException(70001, "获取总订单数失败：" + e.getMessage());
        }
    }

    /**
     * 获取平均客单价
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 平均客单价
     */
    @GetMapping("/avg-amount")
    public BigDecimal getAverageOrderAmount(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        try {
            return orderStatisticsService.getAverageOrderAmount(startTime, endTime);
        } catch (OrderStatisticsException e) {
            throw e;
        } catch (Exception e) {
            throw new OrderStatisticsException(70002, "获取平均客单价失败：" + e.getMessage());
        }
    }
} 